"use strict";

const DbMixin = require("../mixins/db.mixin");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const path = require('path');
/**
 * @typedef {import('moleculer').ServiceSchema} ServiceSchema Moleculer's Service Schema
 * @typedef {import('moleculer').Context} Context Moleculer's Context
 */

/** @type {ServiceSchema} */
module.exports = {
    name: "admin",

    /**
     * Mixins
     */
    // 只保留admin数据库连接用于认证相关操作
    mixins: [DbMixin("admin")],
    
    /**
     * Service created lifecycle event handler
     */
    created() {
    },

    /**
     * Settings
     */
    settings: {
        // Available fields in the responses
        fields: [
            "_id",
            "username",
            "role",
            "permissions"
        ],
        // 配置文件上传目录（相对于项目根目录）
        // 可以通过环境变量 IMAGE_UPLOAD_DIR 覆盖
        uploadDir: process.env.IMAGE_UPLOAD_DIR || "uploads/images",

        // 是否使用日期目录结构 (如: uploads/images/2024/01/15/)
        useDateFolder: true,
        // JWT secret key
        jwtSecret: process.env.JWT_SECRET || "gulu-blog-admin-secret-key",

        // Validator for the `create` & `insert` actions.
        entityValidator: {
            username: "string|min:3",
            password: "string|min:6"
        }
    },

    /**
     * Dependencies
     */
    dependencies: ["blog", "categories", "tags", "images"],

    /**
     * Actions
     */
    actions: {
        // --- AUTHENTICATION ACTIONS ---

        /**
         * User login
         */
        login: {
            cache: false,
            params: {
                username: "string",
                password: "string"
            },
            async handler(ctx) {
                try {
                    const { username, password } = ctx.params;

                    // 管理员登录 - 使用admin数据库
                    const user = await this.adapter.findOne({ username });

                    if (!user || !bcrypt.compareSync(password, user.password)) {
                        this.logger.warn(`登录失败: 用户名 ${username}`);
                        return {
                            code: 401,
                            data: null,
                            message: "用户名或密码错误"
                        };
                    }

                    // Generate JWT token
                    const token = jwt.sign({
                        id: user._id,
                        username: user.username,
                        role: user.role
                    }, this.settings.jwtSecret, {
                        expiresIn: "7d"
                    });
                    await this.broker.cacher.set(`token:${token}`, {
                        id: user._id,
                        username: user.username,
                        role: user.role
                    }, 60 * 60 * 24); // 7天有效期，TTL以秒为单位
                    this.logger.info(`用户登录成功: ${username}`);
                    return {
                        code: 200,
                        data: {
                            token,
                            username: user.username
                        },
                        message: "登录成功"
                    };
                } catch (error) {
                    this.logger.error(`登录过程发生错误: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "登录失败，服务器内部错误"
                    };
                }
            }
        },

        /**
         * Get current user info
         */
        me: {
            rest: "GET /auth/me",
            cache: false,
            async handler(ctx) {
                try {
                    // Check authentication
                    const token = ctx.meta.token;
                    if (!token) {
                        return {
                            code: 401,
                            data: null,
                            message: "Token无效或已过期"
                        };
                    }

                    const decoded = jwt.verify(token, this.settings.jwtSecret);
                    const user = await this.adapter.findById(decoded.id);

                    if (!user) {
                        this.logger.warn(`Token验证失败: 用户不存在 ${decoded.id}`);
                        return {
                            code: 404,
                            data: null,
                            message: "用户不存在"
                        };
                    }

                    return {
                        code: 200,
                        data: {
                            id: user._id.toString(),
                            username: user.username,
                            role: user.role,
                            permissions: user.permissions || []
                        },
                        message: "success"
                    };
                } catch (error) {
                    this.logger.error(`Token验证失败: ${error.message}`, error);
                    return {
                        code: 401,
                        data: null,
                        message: "Token无效或已过期"
                    };
                }
            }
        },

        /**
         * User logout
         */
        logout: {
            rest: "POST /auth/logout",
            cache: false,
            async handler(ctx) {
                try {
                    // 获取当前用户的token
                    const token = ctx.meta.token || ctx.meta.headers?.authorization?.substring(7);
                    
                    if (!token) {
                        return {
                            code: 400,
                            data: null,
                            message: "未提供有效的认证令牌"
                        };
                    }
                    this.broker.cacher.del(`token:${token}`);
                    return {
                        code: 200,
                        data: null,
                        message: "登出成功"
                    };
                } catch (error) {
                    this.logger.error(`登出失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "登出失败"
                    };
                }
            }
        },

        /**
         * Refresh token
         */
        refresh: {
            rest: "POST /auth/refresh",
            cache: false,
            params: {
                token: "string"
            },
            async handler(ctx) {
                try {
                    const decoded = jwt.verify(ctx.params.token, this.settings.jwtSecret);
                    const user = await this.adapter.findById(decoded.id);

                    if (!user) {
                        return {
                            code: 404,
                            data: null,
                            message: "用户不存在"
                        };
                    }

                    // Generate new token
                    const newToken = jwt.sign({
                        id: user._id,
                        username: user.username,
                        role: user.role
                    }, this.settings.jwtSecret, {
                        expiresIn: "7d"
                    });

                    return {
                        code: 200,
                        data: {
                            token: newToken
                        },
                        message: "刷新成功"
                    };
                } catch (error) {
                    this.logger.error(`Token刷新失败: ${error.message}`, error);
                    return {
                        code: 401,
                        data: null,
                        message: "Token无效或已过期"
                    };
                }
            }
        },

        /**
         * Check login status
         */
        status: {
            rest: "GET /auth/status",
            cache: false,
            async handler(ctx) {
                try {
                    const token = ctx.meta.token;

                    if (!token) {
                        return {
                            code: 200,
                            data: {
                                isLoggedIn: false,
                                tokenValid: false,
                                expiresAt: null
                            },
                            message: "success"
                        };
                    }

                    const decoded = jwt.verify(token, this.settings.jwtSecret, { ignoreExpiration: true });
                    const isExpired = Date.now() >= decoded.exp * 1000;

                    return {
                        code: 200,
                        data: {
                            isLoggedIn: !isExpired,
                            tokenValid: !isExpired,
                            expiresAt: isExpired ? null : new Date(decoded.exp * 1000).toISOString()
                        },
                        message: "success"
                    };
                } catch (error) {
                    this.logger.error(`检查登录状态失败: ${error.message}`, error);
                    return {
                        code: 200,
                        data: {
                            isLoggedIn: false,
                            tokenValid: false,
                            expiresAt: null
                        },
                        message: "success"
                    };
                }
            }
        },

        // --- ARTICLE MANAGEMENT ACTIONS ---

        /**
         * Get articles list (Admin)
         */
        getAdminArticles: {
            rest: "GET /articles",
            cache: false,
            async handler(ctx) {
                try {
                    const { page = 1, pageSize = 10, categoryId, tagId, status, keyword, sortBy = "date", order = "desc" } = ctx.params;

                    // 调用blog服务获取文章数据（admin版本，可以看到所有状态）
                    const articles = await ctx.call("blog.getAdminArticles", {
                        category: categoryId ? categoryId.toString() : undefined,
                        tag: tagId ? tagId.toString() : undefined,
                        status: status, // 传递状态参数
                        page,
                        pageSize
                    }, { meta: { $cache: false } });

                    // 处理文章列表，添加分类和标签的详细信息
                    const processedList = articles.data.list.map(article => {
                        const processedArticle = { ...article };
                        // 格式化publishDate
                        if (processedArticle.publishDate) {
                            processedArticle.publishDate = new Date(processedArticle.publishDate).toLocaleString('zh-CN', {
                                year: 'numeric',
                                month: '2-digit',
                                day: '2-digit',
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit'
                            });
                        }

                        // 格式化createdAt和updatedAt
                        if (processedArticle.createdAt) {
                            processedArticle.createdAt = new Date(processedArticle.createdAt).toLocaleString('zh-CN', {
                                year: 'numeric',
                                month: '2-digit',
                                day: '2-digit',
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit'
                            });
                        }
                        if (processedArticle.updatedAt) {
                            processedArticle.updatedAt = new Date(processedArticle.updatedAt).toLocaleString('zh-CN', {
                                year: 'numeric',
                                month: '2-digit',
                                day: '2-digit',
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit'
                            });
                        }

                        return processedArticle;
                    });

                    return {
                        code: 200,
                        data: {
                            list: processedList,
                            total: articles.data.total,
                            page,
                            pageSize,
                            totalPages: Math.ceil(articles.data.total / pageSize)
                        },
                        message: "success"
                    };
                } catch (error) {
                    this.logger.error(`获取文章列表失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "获取文章列表失败"
                    };
                }
            }
        },

        /**
         * Get article detail (Admin)
         */
        getAdminArticleDetail: {
            rest: "GET /articles/:id",
            cache: false,
            params: {
                id: "string"
            },
            async handler(ctx) {
                try {
                    // 调用blog服务获取文章数据（admin版本，可获取任何状态的文章）
                    const result = await ctx.call("blog.getAdminArticleDetail", { id: ctx.params.id });

                    // 如果blog服务返回的是格式化的响应，直接返回
                    if (result && typeof result === 'object' && result.hasOwnProperty('code')) {
                        return result;
                    }

                    // 如果返回的是原始数据，进行格式化
                    if (!result) {
                        return {
                            code: 404,
                            data: null,
                            message: "文章不存在"
                        };
                    }

                    // 格式化文章数据（添加日期格式化）
                    const formattedArticle = {
                        ...result,
                        publishDate: result.publishDate ? new Date(result.publishDate).toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit'
                        }) : null,
                        createdAt: result.createdAt ? new Date(result.createdAt).toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit'
                        }) : null,
                        updatedAt: result.updatedAt ? new Date(result.updatedAt).toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit'
                        }) : null
                    };

                    return {
                        code: 200,
                        data: formattedArticle,
                        message: "success"
                    };
                } catch (error) {
                    this.logger.error(`获取文章详情失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "获取文章详情失败"
                    };
                }
            }
        },

        /**
         * Create article
         */
        createArticle: {
            rest: "POST /articles",
            cache: false,
            params: {
                title: "string|min:2|max:100",
                summary: "string|min:0|max:500",
                content: "string|min:0",
                contentHtml: "string|optional",
                categoryId: "string",
                tagIds: "array",
                status: "string|optional",
                publishDate: "string|optional"
            },
            async handler(ctx) {
                try {
                    const { title, summary, content, contentHtml, categoryId, tagIds = [], status = "draft", publishDate } = ctx.params;

                    // 检查标题是否已存在
                    const existing = await ctx.call("blog.find", { query: { title } }, { meta: { $cache: false } });
                    if (existing && existing.length > 0) {
                        return {
                            code: 422,
                            data: null,
                            message: "文章标题已存在"
                        };
                    }

                    const article = {
                        title,
                        summary,
                        content,
                        contentHtml: contentHtml || '',
                        category: categoryId.toString(),
                        tags: tagIds,
                        status,
                        date: new Date().toISOString().split('T')[0],
                        publishDate: publishDate || (status === "published" ? new Date() : null),
                        views: 0,
                        createdAt: new Date(),
                        updatedAt: new Date()
                    };

                    // 调用blog服务创建文章
                    const result = await ctx.call("blog.create", article, { meta: { $cache: false } });

                    this.logger.info(`文章创建成功: ${title}`);
                    return {
                        code: 200,
                        data: result,
                        message: "添加成功"
                    };
                } catch (error) {
                    this.logger.error(`创建文章失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "创建文章失败"
                    };
                }
            }
        },

        /**
         * Update article
         */
        updateArticle: {
            rest: "PUT /articles/:id",
            cache: false,
            params: {
                id: "string",
                title: "string|optional|min:1|max:100",
                summary: "string|optional|min:1|max:500",
                content: "string|optional|min:1",
                contentHtml: "string|optional",
                categoryId: "string|optional",
                tagIds: "array|optional",
                status: "string|optional",
                publishDate: "string|optional"
            },
            async handler(ctx) {
                try {
                    const { id, ...updateData } = ctx.params;

                    // 检查文章是否存在
                    const article = await ctx.call("blog.get", { id }, { meta: { $cache: false } });
                    if (!article) {
                        return {
                            code: 404,
                            data: null,
                            message: "文章不存在"
                        };
                    }

                    // 检查标题是否被其他文章使用
                    if (updateData.title && updateData.title !== article.title) {
                        const duplicateArticle = await ctx.call("blog.find", {
                            query: {
                                title: updateData.title,
                                _id: { $ne: id }
                            }
                        });
                        if (duplicateArticle && duplicateArticle.length > 0) {
                            return {
                                code: 409,
                                data: null,
                                message: "文章标题已被其他文章使用"
                            };
                        }
                    }

                    // 转换数据格式
                    const updateFields = {};
                    if (updateData.title) updateFields.title = updateData.title;
                    if (updateData.summary) updateFields.summary = updateData.summary;
                    if (updateData.content) updateFields.content = updateData.content;
                    if (updateData.contentHtml !== undefined) updateFields.contentHtml = updateData.contentHtml;
                    if (updateData.categoryId) updateFields.category = updateData.categoryId.toString();
                    if (updateData.tagIds) updateFields.tags = updateData.tagIds;
                    if (updateData.status) {
                        updateFields.status = updateData.status;
                        // 如果状态更新为published且没有publishDate，设置publishDate
                        if (updateData.status === "published" && !article.publishDate && !updateData.publishDate) {
                            updateFields.publishDate = new Date();
                        }
                    }
                    if (updateData.publishDate !== undefined) updateFields.publishDate = updateData.publishDate;
                    updateFields.updatedAt = new Date();

                    const result = await ctx.call("blog.update", { id, ...updateFields }, { meta: { $cache: false } });

                    this.logger.info(`文章更新成功: ${id}`);
                    return {
                        code: 200,
                        data: result,
                        message: "更新成功"
                    };
                } catch (error) {
                    this.logger.error(`更新文章失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "更新文章失败"
                    };
                }
            }
        },

        /**
         * Delete article
         */
        deleteArticle: {
            rest: "DELETE /articles/:id",
            cache: false,
            params: {
                id: "string"
            },
            async handler(ctx) {
                try {
                    // 检查文章是否存在（不增加浏览量）
                    const article = await ctx.call("blog.get", { id: ctx.params.id }, { meta: { $cache: false } });
                    if (!article) {
                        return {
                            code: 404,
                            data: null,
                            message: "文章不存在"
                        };
                    }

                    await ctx.call("blog.remove", { id }, { meta: { $cache: false } });

                    this.logger.info(`文章删除成功: ${ctx.params.id}`);
                    return {
                        code: 200,
                        data: null,
                        message: "删除成功"
                    };
                } catch (error) {
                    this.logger.error(`删除文章失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "删除文章失败"
                    };
                }
            }
        },

        /**
         * Batch delete articles
         */
        batchDeleteArticles: {
            rest: "DELETE /articles/batch",
            cache: false,
            params: {
                ids: "array|min:1|max:100"
            },
            async handler(ctx) {
                try {
                    const { ids } = ctx.params;

                    // 检查文章是否存在
                    const existingArticles = await ctx.call("blog.find", {
                        query: { _id: { $in: ids } }
                    });

                    if (!existingArticles || existingArticles.length === 0) {
                        return {
                            code: 404,
                            data: null,
                            message: "文章不存在"
                        };
                    }

                    const existingIds = existingArticles.map(article => article._id.toString());
                    const nonExistingIds = ids.filter(id => !existingIds.includes(id));

                    if (nonExistingIds.length > 0) {
                        return {
                            code: 404,
                            data: {
                                nonExistingIds
                            },
                            message: `部分文章不存在: ${nonExistingIds.join(', ')}`
                        };
                    }

                    // 逐个删除文章
                    for (const id of ids) {
                        await ctx.call("blog.remove", { id }, { meta: { $cache: false } });
                    }

                    this.logger.info(`批量删除文章成功: ${ids.join(', ')}`);
                    return {
                        code: 200,
                        data: null,
                        message: "批量删除成功"
                    };
                } catch (error) {
                    this.logger.error(`批量删除文章失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "批量删除文章失败"
                    };
                }
            }
        },

        /**
         * Update article status
         */
        updateArticleStatus: {
            rest: "PATCH /articles/:id/status",
            cache: false,
            params: {
                id: "string",
                status: { type: "enum", values: ["published", "draft"] }
            },
            async handler(ctx) {
                try {
                    const { id, status } = ctx.params;

                    // 检查文章是否存在
                    const article = await ctx.call("blog.get", { id }, { meta: { $cache: false } });
                    if (!article) {
                        return {
                            code: 404,
                            data: null,
                            message: "文章不存在"
                        };
                    }

                    const updateData = {
                        id,
                        status,
                        updatedAt: new Date()
                    };

                    // 如果状态更新为published，检查是否需要设置publishDate
                    if (status === "published") {
                        const currentArticle = article;
                        if (!currentArticle.publishDate) {
                            updateData.publishDate = new Date();
                        }
                    }

                    await ctx.call("blog.update", updateData, { meta: { $cache: false } });

                    this.logger.info(`文章状态更新成功: ${id} -> ${status}`);
                    return {
                        code: 200,
                        data: null,
                        message: "状态更新成功"
                    };
                } catch (error) {
                    this.logger.error(`更新文章状态失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "状态更新失败"
                    };
                }
            }
        },

        // --- CATEGORY MANAGEMENT ACTIONS ---

        /**
         * Get categories list
         */
        getCategories: {
            rest: "GET /categories",
            cache: false,
            async handler(ctx) {
                try {
                    // 调用categories服务获取分类数据
                    const categories = await ctx.call("categories.getAdminCategories", {}, { meta: { $cache: false } });

                    return {
                        code: 200,
                        data: categories.data,
                        message: "success"
                    };
                } catch (error) {
                    this.logger.error(`获取分类列表失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "获取分类列表失败"
                    };
                }
            }
        },

        /**
         * Get category detail
         */
        getCategory: {
            rest: "GET /categories/:id",
            cache: false,
            params: {
                id: "string"
            },
            async handler(ctx) {
                try {
                    const category = await ctx.call("categories.get", { id: ctx.params.id }, { meta: { $cache: false } });

                    if (!category) {
                        return {
                            code: 404,
                            data: null,
                            message: "分类不存在"
                        };
                    }

                    return {
                        code: 200,
                        data: {
                            id: category._id.toString(),
                            name: category.name,
                            description: category.description || '',
                            count: category.count || 0,
                            createdAt: category.createdAt ? category.createdAt.toLocaleString('zh-CN') : new Date().toLocaleString('zh-CN'),
                            updatedAt: category.updatedAt ? category.updatedAt.toLocaleString('zh-CN') : new Date().toLocaleString('zh-CN')
                        },
                        message: "success"
                    };
                } catch (error) {
                    this.logger.error(`获取分类详情失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "获取分类详情失败"
                    };
                }
            }
        },

        /**
         * Add category
         */
        addCategory: {
            rest: "POST /categories",
            cache: false,
            params: {
                name: "string|min:1|max:50",
                description: "string|optional|max:200"
            },
            async handler(ctx) {
                try {
                    const { name, description = "" } = ctx.params;

                    // 检查分类名称是否已存在
                    const existing = await ctx.call("categories.find", { query: { name } }, { meta: { $cache: false } });
                    if (existing && existing.length > 0) {
                        return {
                            code: 422,
                            data: null,
                            message: "分类名称已存在"
                        };
                    }

                    const category = {
                        name,
                        description,
                        count: 0,
                        createdAt: new Date(),
                        updatedAt: new Date()
                    };

                    const result = await ctx.call("categories.create", category, { meta: { $cache: false } });

                    this.logger.info(`分类创建成功: ${name}`);
                    return {
                        code: 200,
                        data: {
                            id: result._id.toString(),
                            name: result.name,
                            description: result.description || '',
                            count: result.count || 0,
                            createdAt: result.createdAt.toLocaleString('zh-CN'),
                            updatedAt: result.updatedAt.toLocaleString('zh-CN')
                        },
                        message: "添加成功"
                    };
                } catch (error) {
                    this.logger.error(`创建分类失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "创建分类失败"
                    };
                }
            }
        },

        /**
         * Update category
         */
        updateCategory: {
            rest: "PUT /categories/:id",
            cache: false,
            params: {
                id: "string",
                name: "string|optional|min:1|max:50",
                description: "string|optional|max:200"
            },
            async handler(ctx) {
                try {
                    const { id, ...updateData } = ctx.params;

                    const category = await ctx.call("categories.get", { id }, { meta: { $cache: false } });
                    if (!category) {
                        return {
                            code: 404,
                            data: null,
                            message: "分类不存在"
                        };
                    }

                    if (updateData.name && updateData.name !== category.name) {
                        const existing = await ctx.call("categories.find", {
                            query: {
                                name: updateData.name,
                                _id: { $ne: id }
                            }
                        });
                        if (existing && existing.length > 0) {
                            return {
                                code: 409,
                                data: null,
                                message: "分类名称已被使用"
                            };
                        }
                    }

                    updateData.updatedAt = new Date();
                    const result = await ctx.call("categories.update", { id, ...updateData }, { meta: { $cache: false } });

                    this.logger.info(`分类更新成功: ${id}`);
                    return {
                        code: 200,
                        data: {
                            id: result._id.toString(),
                            name: result.name,
                            description: result.description || '',
                            count: result.count || 0,
                            createdAt: result.createdAt.toLocaleString('zh-CN'),
                            updatedAt: result.updatedAt.toLocaleString('zh-CN')
                        },
                        message: "更新成功"
                    };
                } catch (error) {
                    this.logger.error(`更新分类失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "更新分类失败"
                    };
                }
            }
        },

        /**
         * Delete category
         */
        deleteCategory: {
            rest: "DELETE /categories/:id",
            cache: false,
            params: {
                id: "string"
            },
            async handler(ctx) {
                try {
                    const category = await ctx.call("categories.get", { id: ctx.params.id }, { meta: { $cache: false } });
                    if (!category) {
                        return {
                            code: 404,
                            data: null,
                            message: "分类不存在"
                        };
                    }

                    // 检查分类是否被文章使用
                    const articlesUsingCategory = await ctx.call("blog.find", {
                        query: { category: ctx.params.id }
                    });

                    if (articlesUsingCategory && articlesUsingCategory.length > 0) {
                        return {
                            code: 409,
                            data: null,
                            message: "该分类正在被文章使用，无法删除"
                        };
                    }

                    await ctx.call("categories.remove", { id: ctx.params.id }, { meta: { $cache: false } });

                    this.logger.info(`分类删除成功: ${ctx.params.id}`);
                    return {
                        code: 200,
                        data: null,
                        message: "删除成功"
                    };
                } catch (error) {
                    this.logger.error(`删除分类失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "删除分类失败"
                    };
                }
            }
        },

        /**
         * Get tags list
         */
        getTags: {
            rest: "GET /tags",
            cache: false,
            async handler(ctx) {
                try {
                    // 调用tags服务获取标签数据
                    const tags = await ctx.call("tags.getAdminTags", {}, { meta: { $cache: false } });

                    return {
                        code: 200,
                        data: tags.data,
                        message: "success"
                    };
                } catch (error) {
                    this.logger.error(`获取标签列表失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "获取标签列表失败"
                    };
                }
            }
        },

        /**
         * Delete tag
         */
        deleteTag: {
            rest: "DELETE /tags/:id",
            cache: false,
            params: {
                id: "string"
            },
            async handler(ctx) {
                try {
                    const tag = await ctx.call("tags.get", { id: ctx.params.id }, { meta: { $cache: false } });
                    if (!tag) {
                        return {
                            code: 404,
                            data: null,
                            message: "标签不存在"
                        };
                    }

                    // 检查标签是否被文章使用
                    const articlesUsingTag = await ctx.call("blog.find", {
                        query: { tags: ctx.params.id }
                    });

                    if (articlesUsingTag && articlesUsingTag.length > 0) {
                        return {
                            code: 409,
                            data: null,
                            message: "该标签正在被文章使用，无法删除"
                        };
                    }

                    await ctx.call("tags.remove", { id: ctx.params.id }, { meta: { $cache: false } });

                    this.logger.info(`标签删除成功: ${ctx.params.id}`);
                    return {
                        code: 200,
                        data: null,
                        message: "删除成功"
                    };
                } catch (error) {
                    this.logger.error(`删除标签失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "删除标签失败"
                    };
                }
            }
        },

        // --- SETTINGS MANAGEMENT ACTIONS ---

        /**
         * Get personal info
         */
        getPersonalInfo: {
            rest: "GET /settings/personal",
            cache: false,
            async handler(ctx) {
                try {
                    // 从blog服务获取个人信息
                    const personalInfo = await ctx.call("blog.getPersonalInfo", {}, { meta: { $cache: false } });

                    return {
                        code: 200,
                        data: personalInfo,
                        message: "success"
                    };
                } catch (error) {
                    this.logger.error(`获取个人信息失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "获取个人信息失败"
                    };
                }
            }
        },

        /**
         * Update personal info
         */
        updatePersonalInfo: {
            rest: "PUT /settings/personal",
            cache: false,
            params: {
                name: "string|optional",
                email: "string|optional",
            },
            async handler(ctx) {
                try {
                    // 将个人信息作为设置保存到 settings 服务
                    const updates = {};
                    Object.entries(ctx.params).forEach(([key, value]) => {
                        if (value !== undefined) {
                            updates[`personal.${key}`] = value;
                        }
                    });

                    if (Object.keys(updates).length > 0) {
                        const result = await ctx.call("settings.updateMultiple", { settings: updates }, { meta: { $cache: false } });
                        this.logger.info(`个人信息更新成功`);
                        return {
                            code: 200,
                            data: ctx.params,
                            message: "个人信息更新成功"
                        };
                    }

                    return {
                        code: 400,
                        data: null,
                        message: "没有提供任何更新信息"
                    };
                } catch (error) {
                    this.logger.error(`更新个人信息失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "更新个人信息失败"
                    };
                }
            }
        },

        /**
         * Upload avatar
         */
        uploadAvatar: {
            rest: "POST /settings/avatar",
            cache: false,
            async handler(ctx) {
                try {
                    this.logger.debug('上传头像', ctx.params);

                    // 从params中获取文件 (通过multer middleware处理)
                    const file = ctx.params.$file || ctx.meta.file || ctx.meta.$multipart?.file;

                    if (!file) {
                        this.logger.warn('未找到上传的文件');
                        return {
                            code: 400,
                            data: null,
                            message: "请上传头像文件"
                        };
                    }
                    let relativePath;
                    if (this.settings.useDateFolder) {
                        // 使用日期目录结构
                        const now = new Date();
                        const year = now.getFullYear();
                        const month = String(now.getMonth() + 1).padStart(2, '0');
                        const day = String(now.getDate()).padStart(2, '0');
                        relativePath = path.join(
                            this.settings.uploadDir,
                            year.toString(),
                            month,
                            day,
                            file.filename
                        ).replace(/\\/g, '/');
                    } else {
                        // 使用固定目录
                        relativePath = path.join(this.settings.uploadDir, file.filename).replace(/\\/g, '/');
                    }
                    const urlPath = `/${relativePath}`;

                    this.logger.info('文件信息:', {
                        filename: file.filename,
                        originalname: file.originalname,
                        mimetype: file.mimetype,
                        size: file.size,
                        path: file.path,
                        relativePath: relativePath
                    });

                    // 保存图片到images数据库
                    const imageData = {
                        name: file.originalname || 'avatar',
                        originalName: file.originalname,
                        url: urlPath,
                        path: relativePath,
                        size: file.size,
                        mimeType: file.mimetype,
                        width: 0, // 可以后续使用sharp等库获取
                        height: 0, // 可以后续使用sharp等库获取
                        createdAt: new Date(),
                        updatedAt: new Date()
                    };

                    // 调用images服务保存图片信息到数据库
                    const savedImage = await ctx.call("images.create", imageData, { meta: { $cache: false } });

                    // 将头像URL保存到设置中
                    await ctx.call("settings.set", {
                        key: "personal.avatar",
                        value: urlPath
                    }, { meta: { $cache: false } });
                    return {
                        code: 200,
                        data: {
                            url: urlPath,
                            filename: file.filename,
                            originalname: file.originalname,
                            imageId: savedImage._id ? savedImage._id.toString() : savedImage.id
                        },
                        message: "头像上传成功"
                    };
                } catch (error) {
                    this.logger.error(`头像上传失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "头像上传失败: " + error.message
                    };
                }
            }
        },

        /**
         * Change password
         */
        changePassword: {
            rest: "PUT /settings/password",
            cache: false,
            params: {
                oldPassword: "string",
                newPassword: "string|min:6"
            },
            async handler(ctx) {
                try {
                    const { oldPassword, newPassword } = ctx.params;
                    const token = ctx.meta.token;

                    if (!token) {
                        return {
                            code: 401,
                            data: null,
                            message: "未登录"
                        };
                    }

                    const decoded = jwt.verify(token, this.settings.jwtSecret);
                    const user = await this.adapter.findById(decoded.id);

                    if (!user) {
                        return {
                            code: 404,
                            data: null,
                            message: "用户不存在"
                        };
                    }

                    // 验证旧密码
                    if (!bcrypt.compareSync(oldPassword, user.password)) {
                        this.logger.warn(`密码修改失败: 旧密码错误 ${user.username}`);
                        return {
                            code: 400,
                            data: null,
                            message: "旧密码错误"
                        };
                    }

                    // 更新密码
                    const hashedNewPassword = bcrypt.hashSync(newPassword, 10);
                    await this.adapter.updateById(user._id, {
                        $set: { password: hashedNewPassword, updatedAt: new Date() }
                    });

                    this.logger.info(`密码修改成功: ${user.username}`);
                    return {
                        code: 200,
                        data: null,
                        message: "密码修改成功"
                    };
                } catch (error) {
                    this.logger.error(`密码修改失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "密码修改失败"
                    };
                }
            }
        },

        /**
         * Get system settings
         */
        getSystemSettings: {
            rest: "GET /settings/system",
            cache: false,
            async handler(ctx) {
                try {
                    // 从settings服务获取系统设置
                    const settings = await ctx.call("settings.getSystemSettings", {}, { meta: { $cache: false } });

                    return {
                        code: 200,
                        data: settings.data,
                        message: "success"
                    };
                } catch (error) {
                    this.logger.error(`获取系统设置失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "获取系统设置失败"
                    };
                }
            }
        },

        /**
         * Update system settings
         */
        updateSystemSettings: {
            rest: "PUT /settings/system",
            cache: false,
            params: {
                siteName: "string|optional",
                description: "string|optional",
                keywords: "string|optional",
                recordInfo: "object|optional"
            },
            async handler(ctx) {
                try {
                    const result = await ctx.call("settings.updateSystemSettings", ctx.params, { meta: { $cache: false } });

                    this.logger.info('系统设置更新成功');
                    return result;
                } catch (error) {
                    this.logger.error(`更新系统设置失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "更新系统设置失败"
                    };
                }
            }
        },

        // --- DASHBOARD ACTIONS ---

        /**
         * Get dashboard stats
         */
        getDashboardStats: {
            rest: "GET /dashboard/stats",
            cache: false,
            async handler(ctx) {
                try {
                    // 获取文章统计
                    const allArticles = await ctx.call("blog.find", {}, { meta: { $cache: false } });

                    const totalArticles = allArticles.length;
                    const publishedArticles = allArticles.filter(article => article.status === "published").length;
                    const draftArticles = allArticles.filter(article => article.status === "draft").length;

                    // 获取分类统计
                    const categories = await ctx.call("categories.getAdminCategories", {}, { meta: { $cache: false } });
                    const totalCategories = categories.data.length;

                    // 获取标签统计
                    const tags = await ctx.call("tags.getAdminTags", {}, { meta: { $cache: false } });
                    const totalTags = tags.data.length;

                    // 获取今日文章（简化处理）
                    const today = new Date().toISOString().split('T')[0];
                    const todayArticles = allArticles.filter(article => article.date === today).length;

                    // 获取今日浏览量（简化处理）
                    const todayViews = allArticles.filter(article => article.date === today).reduce((sum, article) => sum + (article.views || 0), 0);

                    // 获取最近7天的文章统计
                    const last7Days = [];
                    for (let i = 6; i >= 0; i--) {
                        const date = new Date();
                        date.setDate(date.getDate() - i);
                        const dateStr = date.toISOString().split('T')[0];
                        const count = allArticles.filter(article => article.date === dateStr).length;
                        last7Days.push({ date: dateStr, count });
                    }

                    // 获取最新5篇文章
                    const latestArticles = allArticles.slice(0, 5).map(article => ({
                        id: article.id,
                        title: article.title,
                        date: article.date,
                        status: article.status,
                        views: article.views || 0
                    }));

                    return {
                        code: 200,
                        data: {
                            totalArticles,
                            totalCategories,
                            totalTags,
                            publishedArticles,
                            draftArticles,
                            todayViews,
                            todayArticles,
                            last7Days,
                            latestArticles
                        },
                        message: "success"
                    };
                } catch (error) {
                    this.logger.error(`获取统计数据失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "获取统计数据失败"
                    };
                }
            }
        },

        /**
         * Get dashboard chart data
         */
        getDashboardChart: {
            rest: "GET /dashboard/chart",
            cache: false,
            async handler(ctx) {
                try {
                    // 获取文章统计
                    const allArticles = await ctx.call("blog.find", {}, { meta: { $cache: false } });

                    // 获取最近30天的文章统计
                    const last30Days = [];
                    for (let i = 29; i >= 0; i--) {
                        const date = new Date();
                        date.setDate(date.getDate() - i);
                        const dateStr = date.toISOString().split('T')[0];
                        const count = allArticles.filter(article => article.date === dateStr).length;
                        const views = allArticles.filter(article => article.date === dateStr).reduce((sum, article) => sum + (article.views || 0), 0);

                        last30Days.push({
                            date: dateStr,
                            articles: count,
                            views: views
                        });
                    }

                    // 获取分类分布统计
                    const categories = await ctx.call("categories.getAdminCategories", {}, { meta: { $cache: false } });
                    const categoryStats = categories.data.map(cat => ({
                        name: cat.name,
                        value: cat.count
                    }));

                    // 获取标签分布统计（取前10个）
                    const tags = await ctx.call("tags.getAdminTags", {}, { meta: { $cache: false } });
                    const tagStats = tags.data
                        .sort((a, b) => b.count - a.count)
                        .slice(0, 10)
                        .map(tag => ({
                            name: tag.name,
                            value: tag.count
                        }));

                    return {
                        code: 200,
                        data: {
                            timeline: last30Days,
                            categoryDistribution: categoryStats,
                            tagDistribution: tagStats
                        },
                        message: "success"
                    };
                } catch (error) {
                    this.logger.error(`获取图表数据失败: ${error.message}`, error);
                    return {
                        code: 500,
                        data: null,
                        message: "获取图表数据失败"
                    };
                }
            }
        }
    },

    /**
     * Methods
     */
    methods: {
        /**
         * Authenticate user
         */
        async authenticate(ctx) {
            const auth = ctx.meta.authorization;
            if (!auth) {
                throw new Error("未授权");
            }

            const token = auth.replace("Bearer ", "");
            try {
                const decoded = jwt.verify(token, this.settings.jwtSecret);
                ctx.meta.user = decoded;
                ctx.meta.token = token;
            } catch (error) {
                throw new Error("Token无效或已过期");
            }
        }
    },

    /**
     * Events
     */
    events: {},

    /**
     * Service created lifecycle event handler
     */
    created() { },

    /**
     * Service started lifecycle event handler
     */
    async started() {
        // 检查是否已存在管理员账号
        const adminCount = await this.adapter.count({ role: "admin" });

        if (adminCount === 0) {
            // 创建默认管理员账号
            const defaultAdmin = {
                username: "admin",
                password: bcrypt.hashSync("admin123", 10), // 默认密码：admin123
                role: "admin",
                permissions: ["all"],
                createdAt: new Date()
            };

            try {
                await this.adapter.insert(defaultAdmin);
                this.logger.info("默认管理员账号已创建：用户名：admin，密码：admin123");
            } catch (error) {
                this.logger.error("创建默认管理员账号失败：", error.message);
            }
        } else {
            this.logger.info("管理员账号已存在，跳过创建");
        }
    },

    /**
     * Service stopped lifecycle event handler
     */
    async stopped() { }
};